//app.js
App({
    onLaunch: function () {
        // 展示本地存储能力
        var logs = wx.getStorageSync('logs') || []
        logs.unshift(Date.now())
        wx.setStorageSync('logs', logs)

        // console.log(wx.getStorageSync('user'));
        if (!wx.getStorageSync('user')) {
            // 登录
            wx.login({
                success: res => {
                    // 发送 res.code 到后台换取 openId, sessionKey, unionId
                    if (res.code) {
                        //发起网络请求
                        wx.request({
                            url: 'https://tongji.yougou520.cn/api/func/get_openid',
                            method: 'POST',
                            data: {
                                code: res.code
                            },
                            success: data => {
                                wx.getUserInfo({
                                    success: function (info) {
                                        wx.request({
                                            url: 'https://tongji.yougou520.cn/api/func/mp_login',
                                            method: 'POST',
                                            data: {
                                                openid: data.data.openid,
                                                city: info.userInfo.city,
                                                country: info.userInfo.country,
                                                province: info.userInfo.province,
                                                language: info.userInfo.language,
                                                oauth: 'mini',
                                                nickName: info.userInfo.nickName,
                                                avatarUrl: info.userInfo.avatarUrl,
                                                gender: info.userInfo.gender,
                                            },
                                            success: function (an) {
                                                console.log(an)
                                                wx.setStorageSync('user', an.data.result);
                                                console.log(data.data.openid);
                                                wx.setStorageSync('open_id', data.data.openid);
                                            }
                                        })
                                    }
                                })
                            }
                        })
                    } else {
                        console.log('获取用户登录态失败！' + res.errMsg)
                    }
                }
            })
        }

    },
    globalData: {
        userInfo: null
        
    }
})